<?php

if (! defined('APP_DIR')) {
  define('APP_DIR', realpath(dirname(__file__)));
  require_once(APP_DIR . '/simplify/simplify.php');
}

require_once(APP_DIR . '/simplify/lib/phpthumb/phpthumb.class.php');

$files_dir = $config['files_dir'];

$route = preg_split('%/%', Request::route(), -1, PREG_SPLIT_NO_EMPTY);

array_shift($route);
$size = array_shift($route);

if (! isset($config['images']['sizes'][$size])) {
  die('Invalid image size');
}

$size = $config['images']['sizes'][$size];

$src = implode('/', $route) . '.' . Request::extension();

$src = urldecode($src);

$width = $size['width'];
$height = $size['height'];
$params = $size['params'];

if (! empty($src) && file_exists($files_dir . '/' . $src)) {
  $filename = '/' . $src;

  if (! empty($width) || ! empty($height) || ! empty($params)) {
    $filename = generate($filename, $width, $height, $params);
  }
}
elseif (isset($config['images']['default'])) {
  $filename = '/' . $config['images']['default'];

  if (! file_exists($files_dir . $filename)) {
    header("HTTP/1.0 404 Not Found");
    exit();
  }

  $filename = generate($filename, $width, $height);
}
else {
  header("HTTP/1.0 404 Not Found");
  exit();
}

$filename = $files_dir . $filename;

if ($getimagesize = @GetImageSize($filename)) {
  header("Cache-Control: private, max-age=10800, pre-check=10800");
  header("Pragma: private");
  header("Expires: " . date(DATE_RFC822, strtotime("2 day")));
  header('Content-Type: ' . phpthumb_functions::ImageTypeToMIMEtype($getimagesize[2]));
}

echo file_get_contents($filename);

exit();

/**
 *
 */

function generate($src, $width = null, $height = null, $params = null)
{
  global $files_dir;

  $phpThumb = new phpThumb();
  $phpThumb->config_cache_directory_depth = 0;
  $phpThumb->config_document_root = $files_dir;
  $phpThumb->config_cache_directory = $files_dir . '/cache';

  if (! is_dir($phpThumb->config_cache_directory)) {
    mkdir($phpThumb->config_cache_directory);
  }

  $phpThumb->setSourceFilename($src);

  if (! empty($width)) {
    $phpThumb->setParameter('w', $width);
  }

  if (! empty($height)) {
    $phpThumb->setParameter('h', $height);
  }

  foreach ((array) $params->getAll() as $param => $value) {
    $phpThumb->setParameter($param, $value);
  }

  $phpThumb->SetCacheFilename();

  if (! is_file($phpThumb->cache_filename)) {
    if (! $phpThumb->GenerateThumbnail()) {
      die($phpThumb->fatalerror);
    }

    if ($phpThumb->RenderToFile($phpThumb->cache_filename) && is_readable($phpThumb->cache_filename)) {
      chmod($phpThumb->cache_filename, 0777);
    }
  }

  $filename = $phpThumb->cache_filename;

  $filename = substr($filename, strlen($files_dir));

  return $filename;
}

?>